package com.ali.common;

import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;

import java.nio.charset.StandardCharsets;

public class Sm3Util {
    /**
     * SM3加密
     */
    public static String encrypt(String content) {
        byte[] contentByte = content.getBytes(StandardCharsets.UTF_8);

        try {
            SM3Digest sm3Digest = new SM3Digest();
            sm3Digest.update(contentByte, 0, contentByte.length);
            byte[] doFinaByte = new byte[sm3Digest.getDigestSize()];
            sm3Digest.doFinal(doFinaByte, 0);
            return HexUtil.encrypt(doFinaByte);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * SM3加密 - 带密钥
     */
    public static String encrypt(String content, String key) {
        byte[] contentByte = content.getBytes(StandardCharsets.UTF_8);
        byte[] keyByte = key.getBytes(StandardCharsets.UTF_8);

        try {
            SM3Digest sm3Digest = new SM3Digest();
            HMac hmac = new HMac(sm3Digest);
            KeyParameter keyParameter = new KeyParameter(keyByte);
            hmac.init(keyParameter);
            hmac.update(contentByte, 0, contentByte.length);
            byte[] doFinalByte = new byte[hmac.getMacSize()];
            hmac.doFinal(doFinalByte, 0);
            return HexUtil.encrypt(doFinalByte);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}